//
//  XycjVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/10.
//

import UIKit
import CoreBluetooth

class XycjVC: BaseVC {

    var sbbh: UILabel!
    
    var onOff: UIView!
    var onLine: UILabel!
    
    var line_view: EWELineView!
    
    var caiji: UIButton!
    
    var time: UILabel!
    var timeNum: Int = 0
    
    var player: EWEPlayer!
    
    var sj_timer: Timer?
    var line_timer: Timer?
    
    //------
    var d_pcm: String = ""
    // 是否停止采集
    var isStop: Bool = true
    
    var isJscjVShow: Bool = false
    
    var isStart: Bool = false
    
    deinit {
        self.stop()
        self.player?.clearData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        player = EWEPlayer.init()
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.onOffLine(_:)), name: NSNotification.Name(rawValue: "ON_OFF_LINE"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataA6(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_A6"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataA6_F(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_A6_F"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.stopLuYin), name: NSNotification.Name(rawValue: "STOP_LU_YIN"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    }
    
    // 采集/结束
    @objc func kscj(_ sender: UIButton) {
        if sender.titleLabel?.text == "开始采集" {
            isStop = false
            start()
        } else if sender.titleLabel?.text == "结束采集" {
            isStop = true
            if player.fdatas.count == 0 {
                SVProgressHUD.showError("未开始采集数据")
                self.stop()
                self.player?.stop()
                self.player.clearData()
                return
            }
            self.stop()
            self.isJscjVShow = true
            JscjV.init().show(self.view) { [weak self] (data) in
                self?.endLy(data)
            }
        }
    }
    
    func endLy(_ data: [String: String]) {
        var datas: Data = self.player.datas as Data
        if self.player.datas.count > 960000 {
            datas = self.player.datas.subdata(with: NSRange.init(location: 0, length: 960000))
        }
        self.isJscjVShow = false
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ON_OFF_LINE"), object: EWEBluetooth.lgf.isOffLine)
        // 判断都是否点了取消，取消则清空临时 pcm 数据
        if data.count == 0 {
            self.player?.stop()
            self.player.clearData()
            self.isStart = false
            return
        }
        // 保存则临时 pcm 文件拷贝至新（PCM）路径并转换成 wav 保存新（WAV）路径
        // 文件处理完毕，将路径（pcm_path， wav_path）保存至本地数据数组
        let pcmfileName = "/听诊样本记录-" + Date.init().lgf_TimeStampString() + ".pcm"
        let pcmfilePath = LGF_Documents_PCM + pcmfileName;
        let fileUrl = URL.init(fileURLWithPath: pcmfilePath)
        do {
            try datas.write(to: fileUrl)
            let wavfileName = "/听诊样本记录-" + Date.init().lgf_TimeStampString() + ".wav";
            let wavfilePath = LGF_Documents_WAV + wavfileName;
            let success = EWEAudio.pcm2Wav(pcmfilePath, outPath: wavfilePath, isDeleteSourchFile: false)
            if success {
                var dataMap = data
                dataMap["pcm_path"] = pcmfileName
                dataMap["wav_path"] = wavfileName
                dataMap["time"] = Date.init().lgf_TimeStampString()
                dataMap["type"] = "心音样本采集"
                dataMap["state"] = "1"
                dataMap["name"] = "循音科技-" + Date.init().lgf_TimeStampString()
                var wavDataArray = UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? []
                wavDataArray.append(dataMap)
                UserDefaults.standard.setValue(wavDataArray, forKey: LGF_BD_WAV_ARRAY)
                SVProgressHUD.showSuccess("数据保存成功")
                Timer.lgf_After(S: 0.2) {
                    self.player.clearData()
                    self.isStart = false
                }
            } else {
                self.removePcm(pcmfilePath)
                self.removePcm(wavfilePath)
                SVProgressHUD.showError("本地数据存在异常，已自动清理缓存，请重新录音")
                self.player.clearData()
                self.isStart = false
            }
        } catch {
            self.removePcm(pcmfilePath)
            SVProgressHUD.showError("本地数据存在异常，已自动清理缓存，请重新录音")
            self.player.clearData()
            self.isStart = false
            debugPrint(error)
        }
    }
    
    func startLy() {
        if self.isStop {
            return
        }
        if self.player.fdatas.length == 0 {
            SVProgressHUD.showError("未获取到数据，检查设备是否就绪，请按一下设备开机键")
            self.stop()
            self.player?.stop()
            self.player.clearData()
        } else {
            self.player.play()
            self.player.pausePlayer = { [weak self] in
                self?.sj_timer?.fireDate = Date.distantFuture
                self?.line_timer?.fireDate = Date.distantFuture
                self?.line_view?.pauseAnimate()
            }
            self.player.startPlayer = { [weak self] in
                self?.sj_timer?.fireDate = Date.distantPast
                self?.line_timer?.fireDate = Date.distantPast
                self?.line_view?.resumeAnimate()
            }
            
            // 时间
            self.sj_timer = Timer.lgf_RunTimer(self, S: 0.02, iS: 49, handler: { [weak self] (timer) in
                self?.timeNum += 1
                if self!.timeNum > 60 {
                    self?.kscj(self!.caiji)
                } else if self!.timeNum <= 60 {
                    self?.time.text = LGFAudioPlayer.getTimeWithNum(self?.timeNum ?? 0)
                }
            })
            
            // 数据采集显示
            self.d_pcm = ""
            self.line_timer = Timer.lgf_RunTimer(self, S: 0.15) { (timer) in
                let arr = self.getStrCountArray(self.d_pcm , 4)
                self.line_view.showLine(arr)
                self.d_pcm = ""
            }
            Timer.lgf_After(S: 0.5) {
                self.line_view?.start()
            }
        }
    }
    
    func start() {
        self.sj_timer?.lgf_StopTimer()
        self.line_timer?.lgf_StopTimer()
        self.player?.clearData()
        EWEFilter.clear()
        caiji.setTitle("结束采集", for: .normal)
        EWEBluetooth.lgf.ly()
    }
    
    func stop() {
        EWEFilter.clear()
        EWEBluetooth.lgf.jslytb()
        line_view?.stop()
        player?.stop()
        caiji.setTitle("开始采集", for: .normal)
        sj_timer?.lgf_StopTimer()
        line_timer?.lgf_StopTimer()
        sj_timer = nil
        line_timer = nil
        timeNum = 0
        time.text = "00:00"
        debugPrint("结束录音")
        debugPrint(Date.init())
        
    }
    
    // 程序推入后台
    @objc func applicationWillResignActive() {
        self.stop()
        self.player?.clearData()
    }

}

extension XycjVC {
    @objc func onOffLine(_ noti: NSNotification) {
        if let isOffLine = noti.object as? Bool {
            if isOffLine && !isJscjVShow {
                self.navigationController?.viewControllers.forEach({ (vc) in
                    if vc is SbVC {
                        self.navigationController?.popToViewController(vc, animated: false)
                    }
                })
            }
        } 
    }
    
    @objc func getDeviceDataA6_F(_ noti: NSNotification) {
        if let data = noti.object as? String {
            d_pcm += data
            let pcmData: Data = (data.hexaData)
            player.fdatas.append(pcmData)
            if !isStart && player.fdatas.count >= 8000  {
                startLy()
                isStart = true
            }
        }
    }
    
    @objc func getDeviceDataA6(_ noti: NSNotification) {
        if let data = noti.object as? String {
            let pcmData: Data = (data.hexaData)
            player.datas.append(pcmData)
        }
    }
    
    @objc func stopLuYin() {
    }

}
